"""
auth:xgt-python
datetime:2021/11/8
爬取快手小姐姐视频
"""
# 1. 确定需求

# 2. 获取数据来源

# 3. 解析数据

import requests  # 发送网络请求

# 发送请求的方式 get post
# post 安全区一些
import re
import json
keyword = input('请输入您想要下载的视频关键字:')
for pcursor in range(1,2):
    data = {
        'operationName': "visionSearchPhoto",
        'query': "query visionSearchPhoto($keyword: String, $pcursor: String, $searchSessionId: String, $page: String, $webPageArea: String) {\n  visionSearchPhoto(keyword: $keyword, pcursor: $pcursor, searchSessionId: $searchSessionId, page: $page, webPageArea: $webPageArea) {\n    result\n    llsid\n    webPageArea\n    feeds {\n      type\n      author {\n        id\n        name\n        following\n        headerUrl\n        headerUrls {\n          cdn\n          url\n          __typename\n        }\n        __typename\n      }\n      tags {\n        type\n        name\n        __typename\n      }\n      photo {\n        id\n        duration\n        caption\n        likeCount\n        realLikeCount\n        coverUrl\n        photoUrl\n        liked\n        timestamp\n        expTag\n        coverUrls {\n          cdn\n          url\n          __typename\n        }\n        photoUrls {\n          cdn\n          url\n          __typename\n        }\n        animatedCoverUrl\n        stereoType\n        videoRatio\n        __typename\n      }\n      canAddComment\n      currentPcursor\n      llsid\n      status\n      __typename\n    }\n    searchSessionId\n    pcursor\n    aladdinBanner {\n      imgUrl\n      link\n      __typename\n    }\n    __typename\n  }\n}\n",
        'variables':{'keyword': keyword, 'pcursor': pcursor, 'page': "search",'searchSessionId': "MTRfMF8xNjM2MzQ2ODkyOTcxX-aFouaRh180MDkx"}

    }

    # 请求头: 伪装python 代码,防止被识别出是爬虫程序
    headers = {

        'accept':'*/*',
        'Accept-Encoding':'gzip, deflate, br',
        'Accept-Language':'zh-CN,zh;q=0.9',
        'Connection':'keep-alive',
        'Content-Length':'1380',
        'content-type':'application/json',
        'Cookie':'kpf=PC_WEB; kpn=KUAISHOU_VISION; clientid=3; did=web_dd09f684c2bd81cccb1b7f4f17b09865',
        'Host':'www.kuaishou.com',
        'Origin':'https://www.kuaishou.com',
        'Referer':'https://www.kuaishou.com/search/video?searchKey=%E6%85%A2%E6%91%87',
        'sec-ch-ua':'"Google Chrome";v="95", "Chromium";v="95", ";Not A Brand";v="99"',
        'sec-ch-ua-mobile':'?0',
        'sec-ch-ua-platform':'"Windows"',
        'Sec-Fetch-Dest':'empty',
        'Sec-Fetch-Mode':'cors',
        'Sec-Fetch-Site':'same-origin',
        'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36'

    }
    # print(type(data))
    data = json.dumps(data)
    # print(type(data))

    url = 'https://www.kuaishou.com/graphql'
    # 我们要登录一个网站 里面可能要输入 账号密码
    # 发送post请求，第一个参数是 链接地址  headers伪装 data
    response= requests.post(url=url, headers=headers, data=data)
    # 2.获取数据
    json_data = response.json()
    # <class 'dict'>  字典类型 {'key':'value'}
    # 字典 键：值
    # ['键'] 拿到：后面的值
    feeds_list = json_data['data']['visionSearchPhoto']['feeds']
    # <class 'list'>: 列表类型 [值1，值2，值3....]
    # [0]: 取第一个值 [1] 取第二个值
    # 取值 当前列表 指定里面的元素类型 java里面是有这个东西 <String>:指定数组当中的数据类型
    # python列表里面是没有的：不管你什么类型的元素都可以
    for feeds in feeds_list:
        # fedds:字典
        # 标题
        title = feeds['photo']['caption']
        # 链接
        photoUrl = feeds['photo']['photoUrl']
        # 在widows操作系统中 我们保存的数据 必须是 没有一些特殊字符的
        # 标题过长？ 字符串切片 >= 256
        new_title = re.sub(r'[\/:*?"<>|\n]','_',title)
    # 4.发送网路请求 请求每一个视频地址  获取视频二进制数据
        mp4_data = requests.get(photoUrl).content
        with open('video/' + new_title + '.mp4',mode='wb') as file:
            file.write(mp4_data)
        print("爬取成功",new_title)






# 5. 通过搜素关键词下载视频 / 指定一个用户的视频 / 翻页下载


